#!/usr/bin/env python3

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

import os
import sys
import glob
import json
import datetime
from munch import Munch

from github3 import login

name_prefix = f'travis-{os.environ["TRAVIS_BUILD_NUMBER"]}-'
label_prefix = f'/travis/{os.environ["TRAVIS_BUILD_NUMBER"]}/'

gh = login(token=os.getenv('GITHUB_TOKEN'))
repo = repo = gh.repository("retorquere", "zotero-better-bibtex")
release = repo.release_from_tag('builds')

action = sys.argv[1]
if action not in ['stash', 'fetch', 'pop']:
  print(f'Unexpected action {json.dumps(action)}')
  sys.exit(1)

generated = [
  'gen/translators.json',
  'gen/preferences/defaults.json',
  'gen/preferences/preferences.json',
  'gen/update.rdf',
]

expired = Munch(
  assets=datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=2),
  builds=datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=7),
)

fetched = []
for asset in release.assets():
  if (asset.label.startswith('/travis/') and asset.created_at < expired.assets) or asset.created_at < expired.builds:
    print(f'Removing expired {asset.label}')
    asset.delete()
    continue

  if not asset.label.startswith(label_prefix):
    continue
 
  if action == 'fetch':
    filename = asset.label[len(label_prefix):]
    print(f'Downloading {asset.label}')
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    with open(filename, 'wb') as f:
      asset.download(f)
    fetched.append(filename)
  else:
    print(f'Removing {asset.label}')
    asset.delete()

if action == 'fetch':
  if len([f for f in fetched if f.endswith('.xpi')]) != 2:
    print('fetch: need 2 xpis')
    sys.exit(1)
  missing = list(set(generated) - set(fetched))
  if len(missing) > 0:
    print('fetch: missing ' + ', '.join(missing))
    sys.exit(1)
  if len(generated) + 2 != len(fetched): # 2 xpis
    print(f'fetch: expected {len(generated) + 2}, got {len(fetched)}')
    sys.exit(1)

if action == 'stash':
  for asset in glob.glob('xpi/*.xpi') + generated:
    print(f'Uploading {asset}')
    with open(asset, 'rb') as f:
      release.upload_asset(
        asset=f,
        name=name_prefix + asset.replace('/', '-'),
        label=label_prefix + asset,
        content_type=('application/x-xpinstall' if asset.endswith('.xpi') else 'application/json')
      )
